/*
 * @Author: C.
 * @Date: 2023-11-30 16:14:12
 */
import { computed, nextTick, ref, toRaw, unref, watch } from 'vue'
export function useListData(props, { dataRef }, emits) {
  const paramsRef = ref({})
  const initParamsRef = ref({})
  const successCb = ref<any>(null)
  const errorCb = ref<any>(null)
  function setParams(params: Recordable) {
    paramsRef.value = { ...paramsRef.value, ...params }
  }
  function getParams() {
    return paramsRef.value
  }
  function initParams(params: Recordable) {
    initParamsRef.value = { ...initParamsRef.value, ...params }
  }
  function setSuccessCb(cb: Fn) {
    successCb.value = cb
  }
  function setErrorCb(cb: Fn) {
    errorCb.value = cb
  }
  function load(params = {}) {
    const apiParams = {
      PageSize: 10,
      CurrentPage: 1,
      ...unref(initParamsRef),
      ...unref(paramsRef),
      ...params,
    }
    unref(props)
      .api(apiParams)
      .then((res: Recordable) => {
        if (apiParams.CurrentPage !== 1) {
          dataRef.value = [...toRaw(dataRef.value), ...res.Items]
        } else {
          dataRef.value = res.Items
        }
        emits('register', dataRef.value)
        // endBySize(res.Items.length, res.Count); //必传参数(当前页的数据个数, 总数据量)
        successCb.value && successCb.value(res.Items.length, res.Count)
      })
      .catch(() => {
        // endErr(); // 请求失败, 结束加载
        errorCb.value && errorCb.value()
      })
  }
  return {
    load,
    setParams,
    initParams,
    setSuccessCb,
    setErrorCb,
    getParams,
  }
}
